package com.example.book_recommend.controller;

import com.example.book_recommend.dao.StoreMapper;
import com.example.book_recommend.entity.Store;
import com.example.book_recommend.pojo.VueResultInfo;
import com.example.book_recommend.pojo.storeInfo.MyPageSearch;
import com.example.book_recommend.pojo.userInfo.VueLoginInfo;
import com.example.book_recommend.service.UserService;
import com.example.book_recommend.service.impl.ShiroServiceImpl;
import com.example.book_recommend.service.impl.StoreServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

@RestController
@EnableAutoConfiguration
@CrossOrigin
@RequestMapping("api/store")
public class StoreController {
    @Autowired
    StoreServiceImpl storeService;

    @Autowired
    ShiroServiceImpl shiroService;

    @Autowired
    StoreMapper storeMapper;

    @RequestMapping(value = "/createStore", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "创建店铺", notes = "创建店铺")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "", defaultValue = "test03", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "password", defaultValue = "e10adc3949ba59abbe56e057f20f883e", required = true, paramType = "query", dataType = "String")
//    })
    public VueResultInfo createStore(@RequestBody @Valid Store store, BindingResult bindingResult,@RequestHeader("token") String token) throws IOException, JSONException {
        if (bindingResult.hasErrors()) {
            String message = String.format("参数错误，详细信息[%s]。", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
            return new VueResultInfo(1,message,null);
        }

        Subject subject= SecurityUtils.getSubject();
        boolean a = subject.hasRole("seller");
        boolean b = subject.isPermitted("store");
        if(!a && !b){
            return new VueResultInfo(1,"你没有这个权限，可怜可怜",null);
        }
        store.setStoreId(null);
        Integer userId = shiroService.findByToken(token).getUserId();
        String storeName = store.getStoreName();
        if(storeName==null){
            return new VueResultInfo(1,"至少需要店铺名字",null);
        }
        if(storeMapper.selectByStoreName(storeName)!=null){
            return new VueResultInfo(1,"有重名店铺了，估计你取名太土",null);
        }
        if(storeMapper.selectByUserId(userId)!=null){
            return new VueResultInfo(1,"你已经有店铺了，做人不要太贪心:-)",null);
        }
        if(store.getStoreManagerId()==null){
            store.setStoreManagerId(userId);
        }
        if((int)store.getStoreManagerId()!=(int)userId){
            return new VueResultInfo(1,"拿着别人的token建自己的店？呵呵不让",null);
        }
        storeMapper.insert(store);

        return new VueResultInfo(0,"建铺成功",null);
    }

    @RequestMapping(value = "/deleteStore", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "删除店铺", notes = "删除店铺")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "", defaultValue = "test03", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "password", defaultValue = "e10adc3949ba59abbe56e057f20f883e", required = true, paramType = "query", dataType = "String")
//    })
    public VueResultInfo deleteStore(@RequestBody @Valid Store store, BindingResult bindingResult, @RequestHeader("token") String token) throws IOException, JSONException {
//        if (bindingResult.hasErrors()) {
//            String message = String.format("参数错误，详细信息[%s]。", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
//            return new VueResultInfo(1,message,null);
//        }

        Integer storeId = store.getStoreId();
        Subject subject= SecurityUtils.getSubject();
        boolean a = subject.hasRole("seller");
        boolean b = subject.isPermitted("store");
        if(!a && !b){
            return new VueResultInfo(1,"你没有这个权限，可怜可怜",null);
        }
        Integer userId = shiroService.findByToken(token).getUserId();
        if(storeId==null){
            storeId = storeMapper.selectByUserId(userId).getStoreId();
        }
        store = storeMapper.selectByPrimaryKey(storeId);
        if(store==null){
            return new VueResultInfo(1,"醒醒，您没店铺",null);
        }
        if((int)store.getStoreManagerId()!=(int)userId){
            return new VueResultInfo(1,"你竟然想删别人家的店铺",null);
        }
        storeService.deleteStore(storeId);

        return new VueResultInfo(0,"删除成功",null);
    }

    @RequestMapping(value = "/updateStore", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "修改店铺", notes = "修改店铺")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "", defaultValue = "test03", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "password", defaultValue = "e10adc3949ba59abbe56e057f20f883e", required = true, paramType = "query", dataType = "String")
//    })
    public VueResultInfo updateStore(@RequestBody @Valid Store store, BindingResult bindingResult,@RequestHeader("token") String token) throws IOException, JSONException {
        if (bindingResult.hasErrors()) {
            String message = String.format("参数错误，详细信息[%s]。", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
            return new VueResultInfo(1,message,null);
        }

        Subject subject= SecurityUtils.getSubject();
        boolean a = subject.hasRole("seller");
        boolean b = subject.isPermitted("store");
        if(!a && !b){
            return new VueResultInfo(1,"你没有这个权限，可怜可怜",null);
        }
        Integer userId = shiroService.findByToken(token).getUserId();
        store.setStoreId(storeMapper.selectByUserId(userId).getStoreId());
        String storeName = store.getStoreName();
        if(storeName==null){
            return new VueResultInfo(1,"至少需要店铺名字",null);
        }
        if((storeMapper.selectByStoreName(storeName)!=null) && (storeMapper.selectByStoreName(storeName).getStoreId()!=store.getStoreId())){
            return new VueResultInfo(1,"有重名店铺了，估计你取名太土",null);
        }
        if(store.getStoreManagerId()==null){
            store.setStoreManagerId(userId);
        }
        if((int)store.getStoreManagerId()!=(int)userId){
            return new VueResultInfo(1,"你没法把店铺转让给别人",null);
        }
        storeService.changeStore(store);

        return new VueResultInfo(0,"修改成功",null);
    }

    @RequestMapping(value = "/getStore", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "获得个人店铺", notes = "获得个人店铺")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "", defaultValue = "test03", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "password", defaultValue = "e10adc3949ba59abbe56e057f20f883e", required = true, paramType = "query", dataType = "String")
//    })
    public VueResultInfo getStore(@RequestHeader("token") String token) throws IOException, JSONException {
        Subject subject= SecurityUtils.getSubject();
        boolean a = subject.hasRole("seller");
        boolean b = subject.isPermitted("store");
        if(!a && !b){
            return new VueResultInfo(1,"你没有这个权限，可怜可怜",null);
        }
        Integer userId = shiroService.findByToken(token).getUserId();
        Store store = storeMapper.selectByUserId(userId);
        if(store==null){
            return new VueResultInfo(1,"醒醒，您没店铺",null);
        }


        return new VueResultInfo(0,"获得成功",store);
    }

    @RequestMapping(value = "/getStoreList", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "获得所有店铺", notes = "获得所有店铺")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "", defaultValue = "test03", required = true, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "password", defaultValue = "e10adc3949ba59abbe56e057f20f883e", required = true, paramType = "query", dataType = "String")
//    })
    public VueResultInfo getStoreList(@RequestBody @Valid MyPageSearch myPageSearch, @RequestHeader("token") String token) throws IOException, JSONException {
        Subject subject= SecurityUtils.getSubject();

        String storeName = "%"+myPageSearch.getStoreName()+"%";
        Integer page = myPageSearch.getPage();
        Integer size = myPageSearch.getSize();

        return new VueResultInfo(0,"获得成功",storeMapper.selectListByPage(storeName,page,size));
    }

}
